package com.utonw.carloan.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sensetime.library.finance.ocr.card.IdCardInfo;
import com.sensetime.library.finance.ocr.card.NativeIdCardSide;
import com.sensetime.sample.a.CardInfoHolder;
import com.sensetime.sample.a.IdCardActivity;
import com.utonw.carloan.R;
import com.utonw.carloan.activity.applyloan.ShowPreviewsImageActivity;
import com.utonw.carloan.activity.base.BaseActivity;
import com.utonw.carloan.function.GlobalLoanFunction;
import com.utonw.carloan.function.UIFunction;
import com.utonw.carloan.global.Constants;
import com.utonw.carloan.global.ReleaseData;
import com.utonw.carloan.utils.FileUtils;
import com.utonw.carloan.utils.ImageUtils;
import com.utonw.carloan.utils.LogUtil;
import com.utonw.carloan.utils.UIUtils;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * Created by SEELE on 2017/3/20.
 */

public abstract class BaseFragment extends Fragment {
    //宿主Activity
    protected BaseActivity mActivity;

    //校验View集合
    private LinkedHashMap<Integer, View> checkViews;

    //获取宿主Activity
    public BaseActivity getHoldingActivity() {
        return mActivity;
    }

    //初始化全局方法
    private UIFunction mUiFunction;

    //上传图片操作成功码
    public static final int UPLOAD_IMAGE_SUCCESS = 666;

    //存储操作图片时当前操作的indicator
    protected ImageView tempIndicator;

    //存储操作图片时当前操作的instruction
    protected TextView tempInstruction;

    //接收图片上传Handler
    protected Handler handler = new Handler(Looper.myLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_IMAGE_SUCCESS:
                    tempIndicator.setImageDrawable(UIUtils.getDrawable(R.mipmap.upload_success));
                    tempInstruction.setText(getString(R.string.apply_page_begin_already_upload));
                    tempInstruction.setTextColor(UIUtils.getColor(R.color.uploadSuccessFontColor));
                    mUiFunction.dissmissProgressDialog();
                    UIUtils.showShortToast("上传图片成功");
                    break;
                default:
                    break;
            }
        }
    };



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (BaseActivity) context;
    }

    public Fragment getFragment() {
        return this;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(setLayout(), container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        checkViews = new LinkedHashMap<>();

        ReleaseData.tempUnused.add(checkViews);
        //初始化
        mUiFunction = new UIFunction();

        initData();

    }

    //绑定布局
    public abstract int setLayout();

    //初始化
    public abstract void initView(View view);

    //逻辑代码
    public abstract void initData();

    public LinkedHashMap<Integer, View> getCheckViews() {
        return checkViews;
    }


    public void setCheckViews(int stringId, View view) {

        getCheckViews().put(stringId, view);

    }

    //校验数据集合
    public boolean checkEmpty() {
        boolean MFlag = true;
        for (Object o : getCheckViews().keySet()) {
            int key = (int) o;
            View viewToCheck = getCheckViews().get(key);
            LogUtil.d(UIUtils.getString(key) + " 是当前选择的Title");
            try {
                if (TextUtils.isEmpty(((EditText) viewToCheck).getText())) {
                    MFlag = false;
                    UIUtils.showShortToast(UIUtils.getString(key) + " 是必填项");
                    LogUtil.d(UIUtils.getString(key) + " 是必填项");
                    break;
                }

            } catch (Throwable e) {
                if (((TextView) viewToCheck).getText().
                        equals(getString(R.string.apply_page_begin_please_choose))) {
                    MFlag = false;
                    UIUtils.showShortToast(UIUtils.getString(key) + " 是必选项");
                    LogUtil.d(UIUtils.getString(key) + " 是必选项");
                    break;
                }
            }
        }

        return MFlag;
    }

    //删除图片后 初始化 图片 对象
    protected void deleteImage(ImageView tempIndicator, TextView tempInstruction) {
        //初始化Image信息
        HashMap<Object, Object> tempMap = (HashMap<Object, Object>) tempInstruction.getTag();
        tempMap.remove("isUpload");
        tempMap.remove("base64");
        tempMap.remove("filePath");
        tempMap.put("isUpload", false);
        tempMap.put("base64", null);
        tempMap.put("filePath", null);
        tempIndicator.setImageDrawable(UIUtils.getDrawable(R.mipmap.camera));
        tempInstruction.setText(getString(R.string.apply_page_begin_please_choose));
        tempInstruction.setTextColor(UIUtils.getColor(R.color.colorLightGray));
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取通过相册返回的图片URI
        if (requestCode == Constants.REQUEST_ALBUM && resultCode == RESULT_OK) {
            Cursor cursor = getContext().getContentResolver().query(data.getData(), null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                do {
                    mUiFunction.showProgressDialog(getContext(), "图片上传中");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Message message = Message.obtain();
                            message.what = UPLOAD_IMAGE_SUCCESS;
                            HashMap<Object, Object> tempMap = (HashMap<Object, Object>) tempInstruction.getTag();
                            tempMap.put("isUpload", true);
                            tempMap.put("base64", ImageUtils.bitmapToString(FileUtils.getPath(getContext(), data.getData())));
                            tempMap.put("filePath", FileUtils.getPath(getContext(), data.getData()));
                            handler.sendMessage(message);
                        }
                    }).start();

                } while (cursor.moveToNext());

                cursor.close();
            }


        }


        // TODO: 2017/3/28 上一步，下一步 变换，
        //获取通过相机返回的图片
        if (requestCode == Constants.REQUEST_CAMERA && resultCode == RESULT_OK) {

            LogUtil.d("照相返回的路径");
            LogUtil.d(ReleaseData.tempPathFromCamera);


            try {
                mUiFunction.showProgressDialog(getContext(), "图片上传中");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = Message.obtain();
                        message.what = UPLOAD_IMAGE_SUCCESS;
                        HashMap<Object, Object> tempMap = (HashMap<Object, Object>) tempInstruction.getTag();
                        tempMap.put("isUpload", true);
                        tempMap.put("base64", ImageUtils.bitmapToString(ReleaseData.tempPathFromCamera));
                        tempMap.put("filePath", ReleaseData.tempPathFromCamera);
                        handler.sendMessage(message);
                    }
                }).start();


            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }


            //用户取消拍照
        } else if (requestCode == Constants.REQUEST_CAMERA && resultCode == RESULT_CANCELED) {

            //删除报废的图片
            try {
                new File(ReleaseData.tempPathFromCamera).delete();

            } catch (Throwable e) {
                e.printStackTrace();
            }
            LogUtil.d("用户已取消照相");

        }

        //删除图片，重置图片信息
        if (requestCode == Constants.REQUEST_PREVIEW_IMAGE && resultCode == Constants.RESULT_DELETE_IMAGE) {
            deleteImage(tempIndicator, tempInstruction);
        }

        //修改图片，修改图片信息
        if (requestCode == Constants.REQUEST_PREVIEW_IMAGE && resultCode == Constants.RESULT_CHANGE_IMAGE) {
            final String changedFilePath = data.getStringExtra("changedFilePath");
            mUiFunction.showProgressDialog(getContext(), "图片上传中");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message message = Message.obtain();
                    message.what = UPLOAD_IMAGE_SUCCESS;
                    HashMap<Object, Object> tempMap = (HashMap<Object, Object>) tempInstruction.getTag();
                    tempMap.put("isUpload", true);
                    tempMap.put("base64", ImageUtils.bitmapToString(changedFilePath));
                    tempMap.put("filePath", changedFilePath);
                    handler.sendMessage(message);
                }
            }).start();
        }


        //三方扫描身份证、银行卡
        if (requestCode == Constants.REQUEST_CODE_RESULT) {
            return;
        }
        switch (resultCode) {
            case RESULT_CANCELED:
                UIUtils.showShortToast(getString(R.string.canceled));
                break;
            case IdCardActivity.RESULT_CODE_NO_PERMISSIONS:
            case IdCardActivity.RESULT_CODE_CAMERA_ERROR:
                UIUtils.showShortToast(getString(R.string.error_camera));
                break;
            case IdCardActivity.RESULT_CODE_LICENSE_FILE_NOT_FOUND:
                UIUtils.showShortToast(getString(R.string.license_file_not_found));
                break;
            case IdCardActivity.RESULT_CODE_WRONG_STATE:
            case IdCardActivity.RESULT_CODE_NO_LISTENER_SET:
                UIUtils.showShortToast(getString(R.string.error_wrong_state));
                break;
            case IdCardActivity.RESULT_CODE_LICENSE_EXPIRE:
                UIUtils.showShortToast(getString(R.string.license_expire));
                break;
            case IdCardActivity.RESULT_CODE_LICENSE_PACKAGE_NAME_MISMATCH:
                UIUtils.showShortToast(getString(R.string.error_package_name));
                break;
            case IdCardActivity.RESULT_CODE_CHECK_LICENSE_FAIL:
                UIUtils.showShortToast(getString(R.string.license_invalid));
                break;
            case IdCardActivity.RESULT_CODE_TIMEOUT:
                UIUtils.showShortToast(getString(R.string.timeout));
                break;
            case IdCardActivity.RESULT_CODE_CHECK_MODEL_FAIL:
                UIUtils.showShortToast(getString(R.string.model_fail));
                break;
            case IdCardActivity.RESULT_CODE_MODEL_FILE_NOT_FOUND:
                UIUtils.showShortToast(getString(R.string.model_not_found));
                break;
            case IdCardActivity.RESULT_CODE_ERROR_API_KEY_SECRET:
                UIUtils.showShortToast(getString(R.string.error_api_key_secret));
                break;
            case IdCardActivity.RESULT_CODE_SERVER:
                UIUtils.showShortToast(getString(R.string.error_server));
                break;
            case Activity.RESULT_OK:
                IdCardInfo idCardInfo = CardInfoHolder.getCardInfo();

                if (idCardInfo == null) {
                    return;
                }
                switch (idCardInfo.getSide()) {
                    case NativeIdCardSide.CV_FINANCE_IDCARD_SIDE_BACK:
                        getIdcardBackInfo(idCardInfo);
                        break;
                    case NativeIdCardSide.CV_FINANCE_IDCARD_SIDE_FRONT:
                        getIdcardFrontInfo(idCardInfo);
                        break;
                    case NativeIdCardSide.CV_FINANCE_IDCARD_SIDE_UNKNOWN:
                        getIdcardFrontInfo(idCardInfo);
                        break;
                }
                break;
            case 0x73:
                if (null != data) {
                    getBankcardInfo(data);
                }else {
                    UIUtils.showShortToast(getString(R.string.please_reupload));
                }
                break;
            case 0x74:
                if (null != data) {
                    getCreditcardInfo(data);
                }else {
                    UIUtils.showShortToast(getString(R.string.please_reupload));
                }

                break;
        }

    }

    protected abstract void getIdcardFrontInfo(IdCardInfo idCardInfo);

    protected abstract void getIdcardBackInfo(IdCardInfo idCardInfo);

    protected abstract void getBankcardInfo(Intent cardData);

    protected abstract void getCreditcardInfo(Intent cardData);


    //存储上传图片数据
    protected void uploadImageData(GlobalLoanFunction globalLoanFunction, ImageView mIndicator, TextView mInstruction, int sTitle) {
        HashMap<Object, Object> tempMap = (HashMap<Object, Object>) mInstruction.getTag();
        if ((Boolean) tempMap.get("isUpload")) {
            Intent intent = new Intent(getContext(), ShowPreviewsImageActivity.class);
            intent.putExtra("filePath", (String) tempMap.get("filePath"));
            intent.putExtra("sTitle", sTitle);

            tempIndicator = mIndicator;
            tempInstruction = mInstruction;
            this.startActivityForResult(intent, Constants.REQUEST_PREVIEW_IMAGE);
        } else {
            tempIndicator = mIndicator;
            tempInstruction = mInstruction;
            globalLoanFunction.showGetImageDialog(getContext(), getFragment(), new GlobalLoanFunction.SendPathInterface() {
                @Override
                public void sendCamFilePath(String path, Uri mImageUri) {
                    ReleaseData.tempPathFromCamera = path;
                    ReleaseData.tempUriFromCamera = mImageUri;

                }
            });
        }
    }

}
